<template>
	<view class="wanl-order-list">
		<!-- 求购按钮 -->
		   <button class="buy-btn" @tap="showPopup = true">求购</button>
				
		<view class="navbar">
			<view class="nav-item text-df" v-for="(item, index) in navList" :key="item.state" :class="{ current: tabCurrentIndex === index }" @tap="tabClick(index)">
				{{ item.text }}
			</view>
		</view>
		<swiper :current="tabCurrentIndex" style="height: calc(100% - 80rpx)" duration="300" @change="changeTab">
			<swiper-item class="tab-content" v-for="(tag, key) in navList" :key="tag.state">
				<scroll-view class="list-scroll-content" scroll-y @scrolltolower="loadData">
					<!-- 空白页 -->
					<wanl-empty text="没有找到任何订单"v-if="tag.loaded === true && tag.orderList.length === 0"/>
					<!-- 订单列表 -->
					<view v-for="(o, okey) in tag.orderList" :key="o.id" class="order-item radius-bock">
						<view class="head">
							<view class="shop wanl-gray" >
								<text class="wlIcon-dianpu1 wanl-black"></text>
								<text class="wanl-black margin-lr-xs text-30">挂售</text>
								<text class="wlIcon-fanhuigengduo text-sm"></text>
							</view>
							<view class="margin-right-bj text-sm">
								<text class="state" :style="{ color: o.stateTipColor }">{{ o.stateTip }}</text>
								<text v-if="o.state === 7" class="margin-left-sm wlIcon-lajitong" @tap="deleteOrder(o.id,okey)"></text>
							</view>
						</view>
						<!-- 商品 -->
						<view class="goods-box"  @tap="orderDetails(o.id)">
							<view class="cu-avatar xl margin-right-bj radius" :style="{backgroundImage: 'url('+$wanlshop.oss(o.image, 70, 70)+')'}"> </view>
							<view class="content margin-right-bj">
								<view class="describe">
									<view class="text-cut-2">
										单号:N2PN4261{{o.id}}
									</view>
									<view class="wanl_sku text-min">
										<text class="wanl-gray-dark">{{o.status}}</text>
									</view>
								</view>
								<view class="parameter">
									<view class="text-price text-sm text-black">
										{{ o.price }}
									</view>
									<view class="text-min wanl-gray">
										x {{ o.val }}
									</view>
								
								</view>
							</view>
						</view>
						<!-- 底部 -->
						<view class="price-box text-sm flex" >
							<view  class="margin-right-sm wanl-gray">手续费：<text class="text-price">1%</text></view>
							<view>实付款：<text class="text-price">{{ o.amount }}</text></view>
						</view>
					
						<view class="action-box padding-bottom-bj" >
							<!-- <button class="cu-btn round line-black" @tap="toChat(order.shop_id)">联系商家</button> -->
							<button class="cu-btn round margin-lr-bj wanl-bg-orange" @tap="sell(o.id)">兑换</button>
						</view>
			
					</view>
					<uni-load-more :status="tag.loadingType" :content-text="contentText"/>
					<view class="edgeInsetBottom"></view> 
				</scroll-view>
			</swiper-item>
		</swiper>
	
		
		    <!-- 弹窗 -->
		    <uni-popup v-if="showPopup" type="bottom" :is-mask-click="true" @maskClick="showPopup = false">
		      <view class="popup-content">
		        <!-- 数量输入 -->
		        <view class="input-group">
		          <text class="label">数量：</text>
		          <input 
		            v-model="number" 
		            class="input" 
		            type="number" 
		            placeholder="请输入数量"
		            @input="calculateTotal"
		          />
		        </view>
		
		        <!-- 单价输入 -->
		        <view class="input-group">
		          <text class="label">单价：</text>
		          <input
		            v-model="price"
		            class="input"
		            type="number"
		            placeholder="请输入单价"
		            @input="calculateTotal"
		          />
		        </view>
		
		        <!-- 总价显示 -->
		        <view class="total-price">总价：{{ total }}元</view>
		
		        <!-- 提交按钮 -->
		        <button class="submit-btn" @tap="buy">提交</button>
		      </view>
		    </uni-popup>
	</view>
</template>

<script>
export default {
	data() {
		return {
			tabCurrentIndex: 0,
			navList: [
				{
					state: 0,
					text: '可兑换',
					loadingType: 'more',
					current_page: 1,
					orderList: []
				},
			],
			contentText: {
				contentdown: ' ',
				contentrefresh: '正在加载...',
				contentnomore: ''
			},
			price:1,
			number:1,
			total: 0,
			showPopup:false
		};
	},
	onLoad(options) {
		if (!options.state) {
			options.state = 0;
		}
		this.tabCurrentIndex = +options.state;
		// #ifndef MP
		this.loadData();
		// #endif
		// #ifdef MP
		if (options.state == 0) {
			this.loadData();
		}
		// #endif
	},
	methods: {
		//获取订单列表
		async loadData(source) {
			//这里是将订单挂载到tab列表下
			let index = this.tabCurrentIndex;
			let navItem = this.navList[index];
			let state = navItem.state;
			//判断是否最后一页
			if (navItem.loadingType == 'noMore') {
				return;
			}
			//tab切换只有第一次需要加载数据
			if (source === 'tabChange' && navItem.loaded === true) {
				return;
			}
			//防止重复加载
			if (navItem.loadingType === 'loading') {
				return;
			}
			navItem.loadingType = 'loading';
			// 获取列表
			await uni.request({
				url: '/marketapi/market_list',
				data: {
					state: state,
					page: navItem.current_page
				},
				success: res => {
					navItem.current_page = res.data.current_page; //当前页码
					if (res.data.last_page === res.data.current_page) {
						navItem.loadingType = 'noMore';
					} else {
						navItem.loadingType = 'more';
						navItem.current_page++;
					}
					let orderList = res.data.data.filter(item => {
						//添加不同状态下订单的表现形式
						item = Object.assign(item, this.orderStateExp(item.state));
						//演示数据所以自己进行状态筛选
						if (state === 0) {
							//0为全部订单
							return item;
						}
						return item.state === state;
					});
					orderList.forEach(item => {
						navItem.orderList.push(item);
					});
					//loaded新字段用于表示数据加载完毕，如果为空可以显示空白页
					this.$set(navItem, 'loaded', true);
				}
			});
		},

		//swiper 切换
		changeTab(e) {
			this.tabCurrentIndex = e.target.current;
			this.loadData('tabChange');
		},
		//顶部tab点击
		tabClick(index) {
			this.tabCurrentIndex = index;
		},
		//删除订单
		async deleteOrder(order_id, key) {
			uni.showLoading({
				title: '请稍后'
			});
			await uni.request({
				url: '/wanlshop/order/delOrder',
				method: 'POST',
				data: {
					id: order_id
				},
				success: res => {
					this.navList[this.tabCurrentIndex].orderList.splice(key, 1);
					uni.hideLoading();
				}
			});
		},
		calculateTotal() {
		      const q = parseFloat(this.number) || 0
		      const p = parseFloat(this.price) || 0
		      this.total = (q * p).toFixed(2)
		},
		//求购单
		async buy() {
			uni.showLoading({
				title: '请稍后'
			});
			 if (!this.number || !this.price) {
				uni.showToast({ title: '请填写完整信息', icon: 'none' })
				return
			  }
			  
			  if (this.total <= 0) {
				uni.showToast({ title: '金额必须大于0', icon: 'none' })
				return
			  }
		
			  // 这里添加实际提交逻辑
			  console.log('提交数据：', {
				quantity: this.number,
				price: this.price,
				total: this.total
			  })
		
			  this.showPopup = false
			  
			await uni.request({
				url: '/marketapi/buy',
				method: 'POST',
				data: {
					price:this.price,
					number:this.number
				},
				success: res => {
					this.loadData();
					uni.showToast({ title: res.msg });
					
					uni.hideLoading();
				}
			});
		},
		async sell(oid) {
			uni.showLoading({
				title: '请稍后'
			});
			console.log("oid",oid);
			await uni.request({
				url: '/marketapi/sell',
				method: 'POST',
				data: {
					id: oid
				},
				success: res => {	
					this.loadData();
					uni.showToast({ title: res.msg });
					uni.hideLoading();
				}
			});
		},
	
		//订单状态文字和颜色
		orderStateExp(state) {
			let stateTip = '',
				stateTipColor = '#333';
			switch (+state) {
				case 1:
					stateTip = '等待支付';
					stateTipColor = '#f40';
					break;
				case 2:
					stateTip = '等待卖家发货';
					break;
				case 3:
					stateTip = '卖家已发货';
					break;
				case 4:
					stateTip = '交易成功';
					break;
				case 5:
					stateTip = '交易成功';
					break;
				case 6:
					stateTip = '已完成';
					break;
				case 7:
					stateTip = '订单已关闭';
					stateTipColor = '#777';
					break;
				//更多自定义
			}
			return {
				stateTip,
				stateTipColor
			};
		},
		// 修改地址
		editAddress(id) {
			this.$wanlshop.to('/pages/user/address/address?source=2&order_id=' + id);
		},
		
	}
};
</script>

<style>
page {
	height: 100%;
}

@import "kdjmarket.css";
</style>
